package arithmetic.socket.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 和Test3有些类似
 * 测试下mmaping的文件写入, 并思考编解码的问题
 */
public class NioTestCharset {
    public static void main(String[] args) throws Exception {

        //test1();
        test2();
    }

    private static void test1 ()throws Exception{
        RandomAccessFile readFile =
                new RandomAccessFile("src/main/java/arithmetic/socket/nio/nioCharsetInput.txt", "r");
        RandomAccessFile randomAccessFile =
                new RandomAccessFile("src/main/java/arithmetic/socket/nio/nioCharsetOutput.txt", "rw");
        FileChannel writeChannel = randomAccessFile.getChannel();
        MappedByteBuffer mappedByteBuffer = writeChannel.map(MapMode.READ_WRITE,0,readFile.length());
        FileChannel channel = readFile.getChannel();
        channel.read(mappedByteBuffer);

        //ByteBuffer encode = charset.encode(readFile.readLine());
        Charset charset = StandardCharsets.UTF_8;
        // readChannel.write(mappedByteBuffer);

        //CharBuffer decode = charset.decode(encode);

        //mappedByteBuffer.put(s.getBytes());
        // CharBuffer charBuffer = CharBuffer.allocate(1024);

        //randomAccessFile.write(s.getBytes());
        //mappedByteBuffer.put(s.getBytes());
        writeChannel.close();
        readFile.close();
        randomAccessFile.close();
    }

    /**
     * 开只读 mmap
     * @throws Exception
     */
    private static void test2 ()throws Exception{
        RandomAccessFile readFile =
                new RandomAccessFile("src/main/java/arithmetic/socket/nio/nioCharsetInput.txt", "r");
        RandomAccessFile randomAccessFile =
                new RandomAccessFile("src/main/java/arithmetic/socket/nio/nioCharsetOutput.txt", "rw");

        FileChannel readChannel = readFile.getChannel();
        MappedByteBuffer mappedByteBuffer = readChannel.map(MapMode.READ_ONLY,0,readFile.length());

        //Charset charset = StandardCharsets.UTF_8;
        Charset charset = Charset.forName("GBK");

        CharBuffer charBuffer = charset.decode(mappedByteBuffer);

        System.out.println(charBuffer.toString());
        ByteBuffer outputData = charset.encode(charBuffer);

        // 写入文件
        randomAccessFile.getChannel().write(outputData);

        readFile.close();
        randomAccessFile.close();

    }
}
